#
# This file is a part of the open-eBackup project.
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file, You can obtain one at
# http://mozilla.org/MPL/2.0/.
#
# Copyright (c) [2024] Huawei Technologies Co.,Ltd.
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
#

import os
import re
import uuid

from common.util.exec_utils import su_exec_rm_cmd
from redis.common.const import FormatCapacity, RedisPluginPathConstant, ErrorCode, CommandReturnCode

from redis import log
from common.common import execute_cmd, output_execution_result


def check_path_valid(path):
    pattern = r"[|;&$`<>!\n\\]"
    res = re.search(pattern, path)
    return res is None


def format_capacity_convert(byte_size):
    if byte_size > FormatCapacity.TB_SIZE:
        return f'{round(byte_size / FormatCapacity.TB_SIZE, 3)}TB'
    elif byte_size > FormatCapacity.GB_SIZE:
        return f'{round(byte_size / FormatCapacity.GB_SIZE, 3)}GB'
    elif byte_size > FormatCapacity.MB_SIZE:
        return f'{round(byte_size / FormatCapacity.MB_SIZE, 3)}MB'
    elif byte_size > FormatCapacity.KB_SIZE:
        return f'{round(byte_size / FormatCapacity.KB_SIZE, 3)}KB'
    else:
        return f'{byte_size}B'


def report_job_details(pid, job_detail):
    """
    功能描述：上报任务详情
    参数：
    @pid:pid
    @job_detail: 任务详情
    """
    log.info(f'report job details, pid: {pid}')
    random_uuid = f'redis_{pid}_' + str(uuid.uuid4())
    input_file = os.path.join(RedisPluginPathConstant.TMP_PATH, f'input_{random_uuid}')
    output_file = os.path.join(RedisPluginPathConstant.TMP_PATH, f'output_{random_uuid}')
    output_execution_result(input_file, job_detail.dict(by_alias=True))

    cmd = f'sh {RedisPluginPathConstant.DB_BIN_PATH.value}rpctool.sh ReportJobDetails {input_file} {output_file}'
    code, out, err = execute_cmd(cmd)
    if int(code) != int(ErrorCode.SUCCESS.value):
        log.error(f'report job details, code: {code}, out: {out}, err: {err}')
    with open(output_file, 'r', encoding='utf-8') as file:
        log.info(f'{pid} report result: {file.readlines()}')
    su_exec_rm_cmd(input_file, check_white_black_list_flag=False)
    su_exec_rm_cmd(output_file, check_white_black_list_flag=False)


def execute_cmd_with_timeout(cmd, timeout):
    return execute_cmd(cmd, "utf-8", timeout)
